package com.think.cloud.thinkshop.mall.service.message.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.think.cloud.thinkshop.mall.controller.admin.message.dto.MessageTemplateDTO;
import com.think.cloud.thinkshop.mall.controller.admin.message.dto.MessageTemplateReplaceDTO;
import com.think.cloud.thinkshop.mall.controller.admin.message.param.MessageTemplateUpdateParam;
import com.think.cloud.thinkshop.mall.convert.message.MessageTemplateConvert;
import com.think.cloud.thinkshop.mall.domain.memberuser.MemberUser;
import com.think.cloud.thinkshop.mall.domain.message.MessageTemplate;
import com.think.cloud.thinkshop.mall.domain.message.MessageUserRecord;
import com.think.cloud.thinkshop.mall.enums.message.MessageStatusEnum;
import com.think.cloud.thinkshop.mall.enums.message.MessageTemplateEnum;
import com.think.cloud.thinkshop.mall.mapper.message.MessageTemplateMapper;
import com.think.cloud.thinkshop.mall.service.email.EmailService;
import com.think.cloud.thinkshop.mall.service.memberuser.IMemberUserService;
import com.think.cloud.thinkshop.mall.service.message.IMessageTemplateService;
import com.think.cloud.thinkshop.mall.service.message.IMessageUserRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.think.cloud.thinkshop.common.constant.message.MessageTemplateConstants.*;

/**
 * 系统消息模版配置Service业务层处理
 *
 * @author moxiangrong
 * @date 2024-07-19
 */
@Service
public class MessageTemplateServiceImpl implements IMessageTemplateService {
    @Autowired
    private MessageTemplateMapper messageTemplateMapper;
    @Autowired
    private IMemberUserService memberUserService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private IMessageUserRecordService messageUserRecordService;

    /**
     * 查询系统消息模版配置
     *
     * @param id 系统消息模版配置主键
     * @return 系统消息模版配置
     */
    @Override
    public MessageTemplate selectMessageTemplateById(Long id) {
        return messageTemplateMapper.selectById(id);
    }

    @Override
    public MessageTemplate getMessageTemplate(MessageTemplateEnum messageTemplateEnum) {
        return this.selectMessageTemplateById(messageTemplateEnum.getId());
    }

    @Override
    public MessageTemplateDTO getMessageText(MessageTemplateEnum enums, MessageTemplateReplaceDTO param) {
        MessageTemplate messageTemplate = this.getMessageTemplate(enums);
        MessageTemplateDTO convert = MessageTemplateConvert.INSTANCE.convert(messageTemplate);

        convert.setSpendEmail(replace(messageTemplate.getEmailTemplate(), param));
        convert.setSpendInform(replace(messageTemplate.getInformTemplate(), param));
        return convert;
    }

    @Override
    public Boolean sendMessageText(MessageTemplateEnum enums, MessageTemplateReplaceDTO param, String email) {
        MessageTemplateDTO template = this.getMessageText(enums, param);
        if (template.getUseEmail().equals(MessageStatusEnum.YES.getStatus())) {
            emailService.sendHtmlMail(email, template.getEmailTitle(), template.getSpendEmail());
            return true;
        }
        return false;
    }

    @Override
    @Async
    public void sendMessageText(MessageTemplateEnum enums, MessageTemplateReplaceDTO param, Long userId) {
        MessageTemplateDTO template = this.getMessageText(enums, param);
        if (template.getUseEmail().equals(MessageStatusEnum.YES.getStatus())) {
            MemberUser memberUser = memberUserService.selectMemberUserById(userId);
            emailService.sendHtmlMail(memberUser.getEmail(), template.getEmailTitle(), template.getSpendEmail());
        }
        if (template.getUseInform().equals(MessageStatusEnum.YES.getStatus())) {
            MessageUserRecord build = MessageUserRecord.builder()
                    .userId(userId)
                    .title(template.getInformTitle())
                    .content(template.getSpendInform())
                    .orderId(param.getOrderId())
                    .build();
            messageUserRecordService.insertMessageUserRecord(build);
        }
    }

    //模版替换
    private String replace(String template, MessageTemplateReplaceDTO param) {
        String email = param.getEmail();
        if (email != null) {
            template = template.replace(USER_EMAIL, email);
        }
        String code = param.getCode();
        if (code != null) {
            template = template.replace(V_CODE, code);
        }
        String currencyUnit = param.getCurrencyUnit();
        if (currencyUnit != null) {
            template = template.replace(CURRENCY_UNIT, currencyUnit);
        }
        String payPrice = param.getPayPrice();
        if (payPrice != null) {
            template = template.replace(PAY_PRICE, payPrice);
        }
        String orderCode = param.getOrderCode();
        if (orderCode != null) {
            template = template.replace(ORDER_CODE, orderCode);
        }
        String product = param.getProduct();
        if (product != null) {
            template = template.replace(PRODUCT, product);
        }
        String timeLimit = param.getTimeLimit();
        if (timeLimit != null) {
            template = template.replace(TIME_LIMIT, timeLimit);
        }
        String payLink = param.getPayLink();
        if (payLink != null) {
            template = template.replace(PAY_LINK, payLink);
        }
        String rejectReason = param.getRejectReason();
        if (rejectReason != null) {
            template = template.replace(REJECT_REASON, rejectReason);
        }
        return template;
    }

    /**
     * 查询系统消息模版配置列表
     *
     * @return 系统消息模版配置
     */
    @Override
    public List<MessageTemplate> selectMessageTemplateList() {
        for (MessageTemplateEnum rowEnum : MessageTemplateEnum.values()) {
            Long id = rowEnum.getId();
            MessageTemplate messageTemplate = this.selectMessageTemplateById(id);
            if (messageTemplate == null) {
                MessageTemplate build = MessageTemplateEnum.buildTemplate(rowEnum);
                this.insertMessageTemplate(build);
            }
        }
        return messageTemplateMapper.selectList(new LambdaQueryWrapper<>());
    }

    /**
     * 新增系统消息模版配置
     *
     * @param messageTemplate 系统消息模版配置
     * @return 结果
     */
    @Override
    public int insertMessageTemplate(MessageTemplate messageTemplate) {
        return messageTemplateMapper.insert(messageTemplate);
    }

    /**
     * 修改系统消息模版配置
     *
     * @param messageTemplate 系统消息模版配置
     * @return 结果
     */
    @Override
    public int updateMessageTemplate(MessageTemplateUpdateParam messageTemplate) {
//        messageTemplate.setUpdateTime(DateUtils.getNowDate());
        MessageTemplate build = MessageTemplate.builder()
                .id(messageTemplate.getId())
                .useInform(messageTemplate.getUseInform())
                .useEmail(messageTemplate.getUseEmail())
                .informTitle(messageTemplate.getInformTitle())
                .informTemplate(messageTemplate.getInformTemplate())
                .emailTitle(messageTemplate.getEmailTitle())
                .emailTemplate(messageTemplate.getEmailTemplate())
                .build();
        return messageTemplateMapper.updateById(build);
    }

    /**
     * 批量删除系统消息模版配置信息
     *
     * @param ids 主键集合
     * @return 结果
     */
    @Override
    public int batchDelete(List<Long> ids) {
        return messageTemplateMapper.deleteBatchIds(ids);
    }
}
